package com.atguigu.gmall.item.api;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.feign.list.SkuEsFeignClient;
import com.atguigu.gmall.item.service.SkuDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author 钟涛
 * @version 1.0
 * @description: TODO
 * @date 2021/12/10 11:39
 */
@RestController
@RequestMapping("/api/sku")
public class SkuDetailController {
    @Autowired
    private SkuDetailService skuDetailService;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SkuEsFeignClient esFeignClient;

    /**
     * 商品详情页
     * @param skuId
     * @return
     * @throws Exception
     */
    @RequestMapping("/detail/{id}")
    public Map<String,Object> skuDetails(@PathVariable("id") Long skuId) throws Exception {
        //从分布式缓存中获取，获取不到，回源查库
        Map<String,Object> map = skuDetailService.getSkuDetailsWithAsync(skuId);
        //更新热度分,把es中指定skuId的  hotScore+1
        //方式:累计更新 : 满100给es更新一次
        String hotScoreKey = RedisConst.SKU_HOT_SCORE;
//        Long hotScore = new Long(redisTemplate.opsForHash().get(hotScoreKey,skuId.toString()).toString());
        Long increment = redisTemplate.opsForHash().increment(hotScoreKey,skuId.toString(),1);
        if(increment % 100 == 0){
            //更新es中指定skuId的商品的hotscore属性
            esFeignClient.incrementHotScore(skuId,increment);
        }
        return map;
    }
}
